package org.boulderfoodrescue.webapp.server.login;

import java.util.logging.Logger;

import org.boulderfoodrescue.webapp.client.rpc.LoginService;
import org.boulderfoodrescue.webapp.server.users.UserAccountsDatabase;
import org.boulderfoodrescue.webapp.shared.LoginInfo;
import org.boulderfoodrescue.webapp.shared.UserAccount;
import org.boulderfoodrescue.webapp.shared.UserAccountDetails.AccessLevel;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements LoginService { 
	private static final Logger log = Logger.getLogger(LoginServiceImpl.class.getName());
	
  public LoginInfo login(String requestUri) {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    LoginInfo loginInfo = new LoginInfo();
 
    if (user != null)
    {
    	//User is logged in using google's service
      loginInfo.setLoggedIn(true);
      loginInfo.setEmailAddress(user.getEmail());
      loginInfo.setNickname(user.getNickname());
      UserAccount aUser = UserAccountsDatabase.getUser(user.getEmail());
      if(aUser != null)
      {
      	//User is already in the database
        loginInfo.setAccessLevel(UserAccountsDatabase.getUser(user.getEmail()).getAccessLevel());
        loginInfo.setFirst_name(aUser.getFirstName());
        loginInfo.setLast_name(aUser.getLastName());
        loginInfo.setPhone(aUser.getPhoneNumber());
        loginInfo.setActivated(aUser.isActivated());
      }
      else
      {
      	//User is not in the database
        loginInfo.setActivated(false);
        //Checking to see if the user is one of our admins
        if(userService.isUserAdmin())
        {
        	loginInfo.setAccessLevel(AccessLevel.Admin);
        	log.info("New admin logged in for the first time: "+loginInfo.getEmailAddress());
        }
        else
        {
        	loginInfo.setAccessLevel(AccessLevel.Public);
        	log.info("New public user logged in for the first time: "+loginInfo.getEmailAddress());
        }
        UserAccount new_user = new UserAccount();
        new_user.setEmail(loginInfo.getEmailAddress());
        new_user.setAccessLevel(loginInfo.getAccessLevel());
        new_user.setFirstName("Unknown");
        new_user.setLastName("Uknown");
        UserAccountsDatabase.addUser(new_user);
      }      
    } 
    else
    {
    	//User is not logged in
      loginInfo.setLoggedIn(false);
    }
    loginInfo.setLoginUrl(userService.createLoginURL(requestUri));
    loginInfo.setLogoutUrl(userService.createLogoutURL(requestUri));
    return loginInfo;
  }

}

